package com.xiaoge.libraryuse.table2;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;

import com.flyco.tablayout.SegmentTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.xiaoge.basedevlibrary.base.GuoBaseActivity;
import com.xiaoge.libraryuse.R;
import com.xiaoge.libraryuse.tablelayout.SimpleCardFragment;

import java.util.ArrayList;

public class TableActivity2 extends GuoBaseActivity {

    private SegmentTabLayout mTable;
    private ViewPager mViewPager;

    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private String[] mTitles = {"首页", "消息", "联系人", "更多"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_table2);

        // 初始化填充的fragment
        for (String title : mTitles) {
            mFragments.add(SimpleCardFragment.getInstance("Switch ViewPager " + title));
        }

        initView();
        initTable();
    }

    private void initView() {
        mTable = (SegmentTabLayout) findViewById(R.id.table);
        mViewPager = (ViewPager) findViewById(R.id.view_pager);
    }

    private void initTable() {
        mViewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));

        mTable.setTabData(mTitles);
        mTable.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                mViewPager.setCurrentItem(position);
            }

            @Override
            public void onTabReselect(int position) {
            }
        });

        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                mTable.setCurrentTab(position);
                // 当到此选项卡的时候 清空消息红点
                mTable.hideMsg(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        // 设置默认进入时候的选项
        mViewPager.setCurrentItem(0);
        //设置未读消息红点
        mTable.showDot(1);
    }

    private class MyPagerAdapter extends FragmentPagerAdapter {
        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTitles[position];
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }
    }

}
